package de.elmar_baumann.jbirthdays.ui;

import de.elmar_baumann.jbirthdays.api.Person;
import de.elmar_baumann.jbirthdays.util.Mnemonics;
import de.elmar_baumann.jbirthdays.util.TableUtil;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * @author Elmar Baumann
 */
public class ChoosePersonsDialog extends Dialog {

    private static final long serialVersionUID = 1L;
    private final PersonTableModel allPersonsTablemodel = new PersonTableModel(false, false);
    private final PersonSearchFilter searchFilter = new PersonSearchFilter(allPersonsTablemodel);
    private boolean accepted;

    public ChoosePersonsDialog() {
        this(null);
    }

    public ChoosePersonsDialog(java.awt.Dialog parent) {
        super(parent, true);
        initComponents();
        postInitComponents();
    }

    private void postInitComponents() {
        Mnemonics.setMnemonics(this);
        tablePersons.setDefaultRenderer(Object.class, new PersonsTableCellRenderer());
        tablePersons.setRowSorter(searchFilter.getRowSorter());
        tablePersons.addMouseListener(doubleClickListener);
        textFieldFilterPerson.getDocument().addDocumentListener(searchFilter);
        tablePersons.getSelectionModel().addListSelectionListener(okButtonEnabler);
        TableUtil.restoreColumnWidths("ChoosePersonsDialog.tablePersons", tablePersons, allPersonsTablemodel.getDefaultColumnWidths());
        addWindowListener(closeListener);
    }

    public boolean isAccepted() {
        return accepted;
    }

    /**
     * @param persons persons to choose from
     */
    public void setPersons(Collection<? extends Person> persons) {
        if (persons == null) {
            throw new NullPointerException("persons == null");
        }
        List<Person> sortedPersons = new LinkedList<>(persons);
        Collections.sort(sortedPersons, Person.CMP_ASC_BY_LAST_NAME);
        allPersonsTablemodel.setPersons(sortedPersons);
    }

    public Collection<? extends Person> getSelectedPersons() {
        int[] selectedRows = tablePersons.getSelectedRows();
        List<Person> persons = new ArrayList<>(selectedRows.length);
        for (int selectedRow : selectedRows) {
            int modelRowIndex = tablePersons.convertRowIndexToModel(selectedRow);
            persons.add(allPersonsTablemodel.getPerson(modelRowIndex));
        }
        return persons;
    }

    private boolean isPersonSelected() {
        return tablePersons.getSelectedRowCount() > 0;
    }

    private void selectAll() {
        tablePersons.selectAll();
    }

    private void selectNone() {
        tablePersons.clearSelection();
    }

    private void ok() {
        accepted = isPersonSelected();
        dispose();
    }

    private void cancel() {
        dispose();
    }

    private final ListSelectionListener okButtonEnabler = new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                buttonOk.setEnabled(isPersonSelected());
            }
        }
    };

    private final WindowListener closeListener = new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            TableUtil.persistColumnWidths("ChoosePersonsDialog.tablePersons", tablePersons);
        }
    };

    private final MouseListener doubleClickListener = new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() > 1 && e.getSource() == tablePersons) {
                if (tablePersons.rowAtPoint(e.getPoint()) >= 0) {
                    ok();
                }
            }
        }
    };

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    private void initComponents() {//GEN-BEGIN:initComponents

        scrollPane = new javax.swing.JScrollPane();
        tablePersons = new javax.swing.JTable();
        buttonSelectAll = new javax.swing.JButton();
        buttonSelectNone = new javax.swing.JButton();
        labelFilterPerson = new javax.swing.JLabel();
        textFieldFilterPerson = new javax.swing.JTextField();
        buttonOk = new javax.swing.JButton();
        buttonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("de/elmar_baumann/jbirthdays/ui/Bundle"); // NOI18N
        setTitle(bundle.getString("ChoosePersonsDialog.title")); // NOI18N

        tablePersons.setModel(allPersonsTablemodel);
        scrollPane.setViewportView(tablePersons);

        buttonSelectAll.setText(bundle.getString("ChoosePersonsDialog.buttonSelectAll.text")); // NOI18N
        buttonSelectAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSelectAllActionPerformed(evt);
            }
        });

        buttonSelectNone.setText(bundle.getString("ChoosePersonsDialog.buttonSelectNone.text")); // NOI18N
        buttonSelectNone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSelectNoneActionPerformed(evt);
            }
        });

        labelFilterPerson.setText(bundle.getString("ChoosePersonsDialog.labelFilterPerson.text")); // NOI18N

        textFieldFilterPerson.setColumns(20);

        buttonOk.setText(bundle.getString("ChoosePersonsDialog.buttonOk.text")); // NOI18N
        buttonOk.setEnabled(false);
        buttonOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOkActionPerformed(evt);
            }
        });

        buttonCancel.setText(bundle.getString("ChoosePersonsDialog.buttonCancel.text")); // NOI18N
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollPane)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(buttonSelectAll)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonSelectNone)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelFilterPerson)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textFieldFilterPerson, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                        .addComponent(buttonOk)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(labelFilterPerson)
                        .addComponent(textFieldFilterPerson, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(buttonCancel)
                        .addComponent(buttonOk)
                        .addComponent(buttonSelectAll)
                        .addComponent(buttonSelectNone)))
                .addContainerGap())
        );

        pack();
    }//GEN-END:initComponents

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        cancel();
    }//GEN-LAST:event_buttonCancelActionPerformed

    private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOkActionPerformed
        ok();
    }//GEN-LAST:event_buttonOkActionPerformed

    private void buttonSelectAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSelectAllActionPerformed
        selectAll();
    }//GEN-LAST:event_buttonSelectAllActionPerformed

    private void buttonSelectNoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSelectNoneActionPerformed
        selectNone();
    }//GEN-LAST:event_buttonSelectNoneActionPerformed

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                ChoosePersonsDialog dialog = new ChoosePersonsDialog(null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonOk;
    private javax.swing.JButton buttonSelectAll;
    private javax.swing.JButton buttonSelectNone;
    private javax.swing.JLabel labelFilterPerson;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JTable tablePersons;
    private javax.swing.JTextField textFieldFilterPerson;
    // End of variables declaration//GEN-END:variables

}
